### Artigo: COMO OS DESEMBARGADORES REAGEM A DERROTAS? 
### Autores: Mateus Morais Ara�jo  e Lucas Fernandes de Magalh�es
### C�digos utilizados para gerar os gr�ficos e resultados constantes do artigo


#####################################
###Carregar os pacotes necess�rios###
#####################################

library(tidyverse)
require(stargazer)
require(jtools)
require(broom)
require(ggstance)
library(gridExtra)
library(rio)

#####################
###Carregar a base###
#####################

rm(list=ls())
setwd() #Definir a pasta em que est� salva a base de dados
load("base.rda") #Carregar a base
#bd <- import("base.xlsx")
#bd <- import("base.csv")

options(scipen=2) #Fixar apena duas casas decimais nos outputs


###############
###Gr�fico 1###
###############

#Retira os votos de referencia
bd <- bd %>% filter(voto_referencia==0)

plot1 <- bd %>% group_by(desembargador) %>% mutate(deferente=
                                                       ifelse(sum(voto_desembargador)!=n(),"deferente",
                                                              "n�o-deferente")) %>% 
  distinct(desembargador,.keep_all = T) %>% ungroup() %>% count(deferente) %>% 
  mutate(variavel="N� de desembargadores")%>% 
  rename(valores=deferente)%>%
  ggplot(aes(x=variavel,y=n, fill=valores))+
  geom_col(color="black")+
  geom_text(aes(label=n), color="white",
            position=position_stack(vjust=0.5),
            size=6)+
  theme_classic()+
  theme(axis.text.x = element_blank(),
        axis.title.x = element_text(size=18),
        axis.title.y = element_text(size=18),
        legend.text = element_text(size=18),
        legend.title = element_text(size=18),
  )+
  labs(x="N� de desembargadores", y="Total")+
  scale_fill_manual("Comportamento",values=c("grey","grey21"))

plot2 <- bd %>% mutate(voto_desembargador=ifelse(voto_desembargador==0,"deferente",
                                                    "n�o-deferente")) %>% 
  count(voto_desembargador) %>% 
  mutate(variavel="N� de votos") %>% 
  rename(valores=voto_desembargador) %>%
  ggplot(aes(x=variavel,y=n, fill=valores))+
  geom_col(color="black")+
  geom_text(aes(label=n), color="white",
            position=position_stack(vjust=0.5),
            size=6)+
  theme_classic()+
  theme(axis.text.x = element_blank(),
        axis.title.x = element_text(size=18),
        axis.title.y = element_text(size=18),
        legend.text = element_text(size=18),
        legend.title = element_text(size=18),
        )+
  labs(x="N� de votos", y="Total")+
  scale_fill_manual("Votos",values=c("grey","grey21"))

g1 <- grid.arrange(plot1,plot2, ncol=2)

ggsave('g1.png',g1,width = 30, height = 15, units = "cm")


#################################################
###Tabela descritiva das variaveis categ�ricas###
#################################################

#Total de votos em que a maioria apoia o Des. analisado
a <- bd %>% filter(voto_maioria==1)
b <- nrow(a)/nrow(bd)

#Frequencias
a <- bd %>% mutate(fun��o_julg = ifelse(fun��o_julg==1,"Relator", "Vogal")) %>% 
  count(fun��o_julg) %>% mutate(Vari�vel="Fun��o no Julgamento") %>% 
  rename(valores=fun��o_julg)

b <- bd %>% mutate(tribunal=ifelse(tribunal==1,"TJSP","TJRS")) %>% 
  count(tribunal) %>% mutate(Vari�vel="Tribunal") %>% 
  rename(valores=tribunal)

d <- bd %>% mutate(mat�ria=ifelse(mat�ria==1,"C�vel","Penal")) %>% 
  count(mat�ria) %>% mutate(Vari�vel="Mat�ria") %>% 
  rename(valores=mat�ria)

e <- bd %>% mutate(origem=case_when(
  origem=="quinto"~"Quinto Constitucional",
  origem=="carreira" ~ "Carreira",
  origem=="substituto" ~"Juiz Substituto")) %>% 
  count(origem) %>% mutate(Vari�vel="Origem") %>% 
  rename(valores=origem)

tabela1 <- rbind(a,b,d,e)

tabela1 <- tabela1 %>% mutate(valores=factor(valores,levels = 
                                                       c("Relator","Vogal",
                                                         "TJSP","TJRS",
                                                         "C�vel","Penal",
                                                         "Carreira","Quinto Constitucional",
                                                         "Juiz Substituto"))) %>% 
  group_by(Vari�vel) %>% mutate(freq_rel=round((n/sum(n))*100,2)) %>% 
  rename(freq_abs=2) %>% 
  select(Vari�vel,valores,freq_abs,freq_rel)

export(tabela1,"tab1.xlsx")


###############################################
###Tabela descritiva das variaveis num�ricas###
###############################################

tabela2 <- bd %>% select(9,10,13) %>%gather("Vari�vel","valor") %>% group_by(Vari�vel) %>% 
  summarise(M�nimo=min(valor,na.rm=T),
            Q1=quantile(valor, 0.25,na.rm=T),
            Q2=quantile(valor, 0.50,na.rm=T),
            M�dia=mean(valor, na.rm=T),
            Q3=quantile(valor, 0.75,na.rm=T),
            M�ximo=max(valor,na.rm=T),
            d_padrao=sd(valor,na.rm=T))

export(tabela2,"tab2.xlsx")

#########################
###Modelo de regressao###
#########################


#Ouput das regress�es  - ANEXO 1
reg1 = glm(voto_desembargador ~ estab_oposicao, data = bd, family = binomial)
reg2 = glm(voto_desembargador ~ estab_oposicao + fun��o_julg, data = bd, family = binomial)
reg3 = glm(voto_desembargador ~ estab_oposicao + fun��o_julg + carga_trabalho, data = bd,
           family = binomial)
reg4 = glm(voto_desembargador ~ estab_oposicao + fun��o_julg + carga_trabalho +as.factor(origem),
           data = bd, family = binomial)
reg5 = glm(voto_desembargador ~ estab_oposicao + fun��o_julg + carga_trabalho +as.factor(origem)+
             mat�ria, data = bd, family = binomial)
reg6 = glm(voto_desembargador ~ estab_oposicao + fun��o_julg + carga_trabalho +as.factor(origem)+
             mat�ria + tribunal + tempo_carreira, data = bd, family = binomial)

##Exportar a tabela com os outputs dos modelos
stargazer(reg1, reg2, reg3, reg4, reg5, reg6, type="html", 
          
         coef=list(coef(reg1),coef(reg2),coef(reg3),
                   coef(reg4),coef(reg5), coef(reg6)), p.auto=FALSE, out="logitor5.html")


######################################
#Plots dos coeficientes - Gr�fico 2###
######################################


g2 <- plot_coefs(reg3, reg6, ci_level = 0.95, model.names = c("Sem vari�veis de controles",
                                                              "Com vari�veis de controles"),
           coefs = c("Estabilidade da oposicao" = "estab_oposicao",
                     "Fun��o no julgamento - Relator. Ref: Vogal" = "fun��o_julg",
                     "Carga de trabalho" = "carga_trabalho",
                     "Origem - Quinto Constitucional. Ref: carreira" = "as.factor(origem)quinto",
                     "Origem - Juiz substituto. Ref: carreira" = "as.factor(origem)substituto",
                     "mat�ria -  C�vel. Ref: Criminal" = "mat�ria",
                     "Tribunal - TJSP. Ref: TJRS" = "tribunal",
                     "Tempo de carreira" = "tempo_carreira"),
           legend.title = "Modelos",
           colors = c("grey","grey21"))

g2 <- g2+labs(x="Coeficientes")

ggsave('g2.png',g2,width = 20, height = 10, units = "cm")

###############
###Grafico 3###
###############

g3 <- bd %>% mutate(voto_desembargador=ifelse(voto_desembargador==1,"N�o-deferente","Deferente"),
              oposicao=ifelse(estab_oposicao>0.5,"> 0,5","< 0,5"))  %>%
  count(oposicao, voto_desembargador) %>% group_by(oposicao) %>% 
  mutate(prop=(n/sum(n))*100) %>% 
  rename(`Voto do Desembargador`=voto_desembargador,
         `Estabilidade da oposi��o`=oposicao) %>% 
  ggplot(aes(x=`Estabilidade da oposi��o`, y=prop, fill=`Voto do Desembargador`))+
    geom_col(color="black")+
    geom_text(aes(label=paste0(round(prop,2),"%")), color="white",
              position=position_stack(vjust=0.5), size=6)+
    theme_classic()+
  theme(axis.text.x = element_text(size=15),
        axis.title.x = element_text(size=18),
        axis.title.y = element_text(size=18),
        legend.text = element_text(size=18),
        legend.title = element_text(size=18),
  )+
    labs(x="Estabilidade da oposi��o",y="Propor��o de votos")+
  scale_fill_manual("Votos",values=c("grey","grey21"))

ggsave('g3.png',g3,width = 30, height = 15, units = "cm")



###############
###Gr�fico 4###
###############

g4 <- bd %>% group_by(fun��o_julg) %>% count(voto_desembargador) %>% 
  mutate(fun��o_julg=ifelse(fun��o_julg==1,"Relator","Vogal"),
         voto_desembargador=ifelse(voto_desembargador==1,"N�o-deferente","Deferente"),
         prop=(n/sum(n))*100) %>%
  rename(`Voto do Desembargador`=voto_desembargador) %>% 
  ggplot(aes(x=fun��o_julg,y=prop, fill=`Voto do Desembargador`))+
    geom_col(color="black")+
    geom_text(aes(label=paste0(round(prop,2),"%")), color="white",
              position=position_stack(vjust=0.5),size=6)+
    theme_classic()+
  theme(axis.text.x = element_text(size=15),
        axis.title.x = element_text(size=18),
        axis.title.y = element_text(size=18),
        legend.text = element_text(size=18),
        legend.title = element_text(size=18),
  )+
    labs(x="Fun��o no julgamento",y="Propor��o de votos")+
  scale_fill_manual("Votos",values=c("grey","grey21"))

ggsave('g4.png',g4,width = 30, height = 15, units = "cm")
